﻿var me = this,
    formData = arguments[1],
    emp = PAI.Global.getAccount().employee,
    vm = this.lookupViewModel(),
    draftId = PAI.Global.getUrlData('draftId');

var phone = emp.ext_jlrTelephone;
var employeeNo = emp.employeeNo;
var email = emp.email;

var controller = this.lookupController();
var destInstId = controller.destInstId;
var procInstId = controller.procInstId;

//复制表单ID
var formDataId = PAI.Global.getUrlData('formDataId');
if (me.analysis.status == 'launch' && !draftId && !formDataId) {
    formData.GeneralInformation = {
        Applicant: emp.lastName + " " + emp.firstName,
        DateTime: Ext.Date.format(new Date(), 'Y-m-d'),
        ExpenseType: '3',
        cdsid: employeeNo,
        email: email,
        mobile: phone,
        SingleSource: 'No',
        companyC: 'JLRC',
        fiscalYear: Ext.Date.format(new Date(), 'Y') + '_N'
    };
}
formData.approverDesc = '';

var activity = "";
//查询流程节点
Ext.PAIRest.request({
    url: 'formActivity/currentProcInst',
    ns: PAI.application.userServerUrl,
    method: "POST",
    async: false,
    data: {
        "destInstId": destInstId || '',
        "procInstId": procInstId || ''
    },
    success: function (data) {
        var empId = PAI.Global.getAccount().employee.id;
        for (var i = 0; data.currentActivitys.length > i; i++) {
            controller.currentActivity = data.currentActivitys[i].activityName; //节点名称
            controller.currentActivityId = data.currentActivitys[i].activityId;
            for (var j = 0; j < data.currentActivitys[i].empList.length; j++) {
                controller.employeeId = data.currentActivitys[i].empList[j].employeeId;
                if (empId == controller.employeeId) {
                    activity = controller.currentActivity; //当前节点名称
                }
            }
        }

    },
    failure: function (jsondata) {
    }
});

formData.companySection = formData.companySection || {};
formData.companySection.activity = activity;

if (activity.indexOf('Finance') != -1 || activity.indexOf('CFO') != -1) {
    var company = PAI.Global.getAccount().employee.ext_jlrOrganization;

    if (company) {
        ref.datagrid3.store.on('refresh', function (store) {
            if (!store.isFirstLoadRefresh) {
                store.isFirstLoadRefresh = true;
                store.filterBy(function (item) {
                    return company.indexOf(item.get('Company')) != -1;
                });
            }
        });
    }
}

if (me.analysis.status == 'launch' || me.analysis.status == 'resubmit') {
    var code = '';
    var expenseType = formData.GeneralInformation.ExpenseType;
    switch (expenseType) {
        case '2':
        case '3':
            code = '7f9b174e-a940-4a86-b989-5f962e7e1622';
            break;
        case '6':
            code = 'b3ec2d43-ea96-4052-88bd-6f324ace9790';
            break;
        default:
            break;
    }
    ref.SharingPrinciple.store.removeAll();
    ref.SharingPrinciple.store.code = code;
    ref.SharingPrinciple.store.load();
}

//打印优化
if (me.analysis.status == 'view') {
    //流转记录的数据把中文改成英文
    me.on('beforeprint', function (view, request) {
        var item;
        if (request.history) {
            for (var i = 0; i < request.history.length; i++) {
                item = request.history[i];
                if (item.actInstInfo) {
                    item.destActName = item.actInstInfo.actName;
                } else if (item.destActDisplayName) {
                    item.destActName = language(formCommLang(item.destActDisplayName[PAI.Global.getLanguage()]));
                } else if (item.finalAction == 'PA_ProcStart' || item.finalAction == 'PA_ProcComplete' || item.finalAction == '发起') {
                    item.destActName = language(formCommLang(item.finalAction));
                }
                if (Ext.isObject(item.actionDisplayName)) {
                    item.finalAction = Ext.util.Format.multiLanguage(item.actionDisplayName);
                } else {
                    item.finalAction = formCommLang(item.finalAction);
                }

                item.destName = (item.destLastName || '') + ' ' + (item.destFirstName || '');
            }
        }
        //对数据进行类型进行转化
        if (request.formData) {
            //PurchaseItems
            if (request.formData.PurchaseItems) {
                var PurchaseItems;
                for (var i = 0; i < request.formData.PurchaseItems.length; i++) {
                    PurchaseItems = request.formData.PurchaseItems[i];
                    Ext.each(['Quantity', 'UnitPrice', 'TotalPrice', 'GrossAmount'], function (field) {
                        PurchaseItems[field] = numberToCurrency(PurchaseItems[field]);
                    });
                }
            }
            // PurchaseItemsOuv
            if (request.formData.PurchaseItemsOuv) {
                var PurchaseItemsOuv;
                for (var i = 0; i < request.formData.PurchaseItemsOuv.length; i++) {
                    PurchaseItemsOuv = request.formData.PurchaseItemsOuv[i];
                    Ext.each(['Quantity', 'UnitPrice', 'TotalPrice', 'GrossAmount'], function (field) {
                        PurchaseItemsOuv[field] = numberToCurrency(PurchaseItemsOuv[field]);
                    });
                }
            }
            //CompanyAllocation
            if (request.formData.CompanyAllocation) {
                var CompanyAllocation;
                for (var i = 0; i < request.formData.CompanyAllocation.length; i++) {
                    CompanyAllocation = request.formData.CompanyAllocation[i];
                    //Ext.each(['CompanySharingRatio', 'Cost', 'Balance'], function (field) {
                    //    CompanyAllocation[field] = numberToCurrency(CompanyAllocation[field]);
                    //});
                    CompanyAllocation.CompanySharingRatio = numberToCurrency(CompanyAllocation.CompanySharingRatio);
                    CompanyAllocation.Cost = numberToCurrency(CompanyAllocation.Cost);
                    if (CompanyAllocation.Company == "JLRC") {
                        CompanyAllocation.Balance = numberToCurrency(CompanyAllocation.Balance);
                    } else {
                        CompanyAllocation.Balance = "N/A";
                    }
                }
            }
            //BrandAllocationJLRC
            if (request.formData.BrandAllocationJLRC) {
                var BrandAllocationJLRC;
                for (var i = 0; i < request.formData.BrandAllocationJLRC.length; i++) {
                    BrandAllocationJLRC = request.formData.BrandAllocationJLRC[i];
                    Ext.each(['JASharingRatio', 'JACost', 'LRSharingRatio', 'LRCost'], function (field) {
                        BrandAllocationJLRC[field] = numberToCurrency(BrandAllocationJLRC[field]);
                    });
                }
            }
            //BrandAllocationCJLR
            if (request.formData.BrandAllocationCJLR) {
                var BrandAllocationCJLR;
                for (var i = 0; i < request.formData.BrandAllocationCJLR.length; i++) {
                    BrandAllocationCJLR = request.formData.BrandAllocationCJLR[i];
                    Ext.each(['JASharingRatio', 'JACost', 'LRSharingRatio', 'LRCost'], function (field) {
                        BrandAllocationCJLR[field] = numberToCurrency(BrandAllocationCJLR[field]);
                    });
                }
            }
            // ProjectXAllocation
            if (request.formData.ProjectXAllocation) {
                var ProjectXAllocation;
                for (var i = 0; i < request.formData.ProjectXAllocation.length; i++) {
                    ProjectXAllocation = request.formData.ProjectXAllocation[i];
                    Ext.each(['Amount', 'JAPer', 'JAAmount', 'LRPer', 'JAAmount'], function (field) {
                        ProjectXAllocation[field] = numberToCurrency(ProjectXAllocation[field]);
                    });
                }
            }
            //horizonAllocation
            if (request.formData.horizonAllocation) {
                var horizonAllocation;
                for (var i = 0; i < request.formData.horizonAllocation.length; i++) {
                    horizonAllocation = request.formData.horizonAllocation[i];
                    Ext.each(['Amount', 'JAPer', 'JAAmount', 'LRPer', 'JAAmount'], function (field) {
                        horizonAllocation[field] = numberToCurrency(horizonAllocation[field]);
                    });
                }
            }
        }
        view.request = request;
    });
    me.on('print', function (myDocument, view, jsondata, myWindow) {

        var hiddenField = [];
        var refs = this.lookupController().getReferences();

        for (var name in refs) {
            if (refs[name].hidden) {
                hiddenField.push(name);
            }
        }

        for (var i = 0; i < hiddenField.length; i++) {
            var _el = myDocument.getElementById(hiddenField[i]);
            if (_el) {
                _el.style = 'display:none;';
            }
        }

        var expenseType = formData.GeneralInformation.ExpenseType;

        var purSection = myDocument.getElementById(expenseType == '4' ? 'section41' : 'section40');

        var allDiv = purSection.querySelector('.row').children;

        for (var i in allDiv) {
            allDiv[i].className = 'col col-6';
        }

        //SharingPrinciple打印时增加宽度
        var _width = refs.SharingPrinciple.getEl().getStyle('width').replace('px', '') + 20;
        myDocument.getElementById('SharingPrinciple').style.width = _width + 'px';

        //一些时间单独处理.
        Ext.each(['datetime3', 'datetime4', 'datetime2'], function (field) {
            var datavalue = myDocument.getElementById(field);
            var datatime = datavalue.querySelectorAll('span')[0].innerHTML;
            datavalue.querySelectorAll('span')[0].innerHTML = Ext.Date.format(new Date(datatime), 'Y-m-d');
        });
        //优化流转记录显示
        if (view.request && view.request.history) {
            cache = '<tr><th>Name</th><th>Process Step</th><th>Action</th><th>Start Time</th><th>End Time</th><th>Comments</th></tr>';
            for (var i = 0; i < view.request.history.length; i++) {
                item = view.request.history[i];
                cache = cache + '<tr><td>' +
                    (item.destName || '') +
                    '</td><td>' +
                    (item.destActName || '') +
                    '</td><td>' +
                    (item.finalAction || '') +
                    '</td><td>' +
                    (item.taskStartDate || '') +
                    '</td><td>' +
                    (item.destDate || '') +
                    '</td><td>' +
                    (item.destMessage || '') +
                    '</td></tr>'
            }
        }
    });
}


//定义全局提示函数
controller.showMsgTips = function (errors) {
    if (!Ext.isArray(errors)) {
        errors = [errors];
    }

    Ext.toast({
        html: Ext.String.format('<b>{0}</b><ol><li>{1}</li></ol>', language(formCommLang('formInvaild')), errors.join('</li><li>').replace('<br>', '')),
        minWidth: 350,
        maxWidth: 400,
        align: 't',
        cls: Ext.baseCSSPrefix + 'toast' + ' pai-form-invaild',
        autoCloseDelay: 5000,
        closeOnMouseDown: true
    });
};

/**
 * 
 * @param {any} pa
 * @param {any} record
 * @param {any} fn 
 */
controller.getBalance = function (pa, record, fn) {
    //时时抓取Balance数据
    var budgetitemId = ref.BudgetItems.getValue();
    var isReCall = false;
    controller.budgetControlId = controller.budgetControlId || {};
    var fiscalYearValue = ref.fiscalYear.getValue();
    var year = fiscalYearValue.split('_')[0];

    if (pa) {

        var isInquiryCall = vm.get('NebulogyForm.isInquiryCall');
        var ukCrossCharge = ref.UKCrossCharge.getValue();
        //Enquiry之后不需要实时取最新的Balance.读取公司分摊表格上的Balance.
        if (isInquiryCall == 1 && ['PX', 'JLRCUK'].includes(ukCrossCharge)) {
            //这里可能是采购表格或者公司分摊表格触发.如果是公司分摊表格直接取值就行了.采购的还需要查询下.
            if (record) {
                controller.balance[pa] = record.get('Balance');
                controller.budgetControl[pa] = record.get('budgetControl');
            } else {
                var findRecord = ref.datagrid3.store.findRecord('ProjectActivity', pa);

                controller.balance[pa] = findRecord.get('Balance');
                controller.budgetControl[pa] = findRecord.get('budgetControl');
            }
        } else {
            var paList = vm.get('NebulogyForm.ProjectActivityList');

            var paId = paList.filter((r) => { return r.ProjectActivity == pa })[0].ID;

            Ext.PAIRest.request({
                ns: PAI.application.serviceUrl,
                url: 'jlr-rest/api/budgetFmebugetItem/page',
                method: "POST",
                async: false,
                data: {
                    projectactivityId: paId,
                    budgetitemId: budgetitemId,
                    yearVal: year,
                    company: 'JLRC'
                },
                success: function (data) {

                    if (Ext.isEmpty(data.budgetFmebugetItemF04RespS01s)) {
                        controller.showMsgTips(pa + ' does not have Balance, Please select other Project Activity');

                        //如果record传了 则表示这是Company Allocation编辑触发.查询不到值就取表单上原有的Balance
                        if (record) {

                            controller.balance[pa] = record.get('Balance');
                            controller.budgetControlId[pa] = record.get('budgetControlId');
                            controller.budgetControl[pa] = record.get('budgetControl');
                        }
                        isReCall = true;
                    } else {

                        var curr = data.budgetFmebugetItemF04RespS01s[0];
                        if (curr.valid == 'N') {
                            controller.showMsgTips('The current Balance of ' + pa + ' is Invalid, Please select other Project Activity');

                            isReCall = true;
                        } else {
                            //根据表单Fiscal Year判断是否跨年，数据分为本年及次年两部分。
                            //本年Balance为Budget Control页面当前Balance；
                            //跨年Balance为次年数据Freezing Amount的负值

                            var balance = vm.get('NebulogyForm.IsAcrossYears') ? -curr.freezingAmount.split(',').join('') : curr.balance.split(',').join('');
                            controller.balance[pa] = parseFloat(balance);
                            controller.budgetControlId[pa] = curr.id;
                            controller.budgetControl[pa] = curr.budgetControl;
                        }
                    }
                }
            });
        }
        //调用回调函数
        if (fn && isReCall)
            return fn();
    }
};


if (me.analysis.status == 'launch' || me.analysis.status == 'resubmit') {

    //给所有的numberfield 加上 format:'0,000.00'
    //先遍历所有的表单上的控件 在去遍历 grid 上的控件.
    for (var name in ref) {
        if (ref[name].xtype == 'numberfield') {
            ref[name].format = '0,000.00';
        }
    }

    var setFormat = function (grid) {
        var columns = grid.getColumns();

        for (var i = 0; i < columns.length; i++) {
            if (columns[i].xtype == 'numbercolumn') {
                columns[i].editor.format = '0,000.00';
            }
        }
    };

    setFormat(ref.datagrid2);
    setFormat(ref.datagrid7);
    setFormat(ref.datagrid3);
    setFormat(ref.datagrid4);
    setFormat(ref.datagrid6);
    setFormat(ref.horizonGrid);
}
//将数字转化为千分位
function numberToCurrency(n) {
    Ext.util.Format.thousandSeparator = ',';
    Ext.util.Format.decimalSeparator = '.';
    return Ext.util.Format.number(n, '0,000.00');
}

Ext.PAIRest.request({
    ns: PAI.application.serviceUrl,
    url: 'jlr-rest/api/getFiscalYearList',
    method: "POST",
    async: false,
    data: {},
    success: function (data) {
        var fiscalYearArr = [];
        var value = '';
        for (var i = 0; i < data.years.length; i++) {
            var cur = data.years[i];

            fiscalYearArr.push({
                label: `${cur.yearVal}-${parseInt(cur.yearVal) + 1}`,
                value: `${cur.yearVal}_${cur.crossYear}`
            });
            if (!value && cur.crossYear == 'N') {
                value = `${cur.yearVal}_${cur.crossYear}`;
            }
        }
        ref.fiscalYear.store.loadData(fiscalYearArr);

        if (!formData.GeneralInformation.fiscalYear) {
            formData.GeneralInformation.fiscalYear = value
        }
    }
});
